package com.kexio.file.entity;

import java.time.LocalDateTime;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.kexio.common.entity.BaseEntity;

/**
 * 文件分享链接实体类
 * 
 * 对应数据库表 sys_share_link
 * 存储文件的分享链接信息，支持临时链接和访问控制
 * 
 * @author Kexio Team
 * @since 1.0.0
 */
@TableName("sys_share_link")
public class ShareLink extends BaseEntity {
    
    /**
     * 分享链接ID（主键）- UUID字符串
     */
    @TableId(value = "id", type = IdType.ASSIGN_UUID)
    private String id;
    
    /**
     * 文件ID
     * 关联 sys_file_info 表
     */
    @TableField("file_id")
    private String fileId;
    
    /**
     * 分享码（短链接标识）
     */
    @TableField("share_code")
    private String shareCode;
    
    /**
     * 分享密码（可选）
     */
    @TableField("share_password")
    private String sharePassword;
    
    /**
     * 分享类型：1-公开链接，2-密码链接，3-一次性链接
     */
    @TableField("share_type")
    private Integer shareType;
    
    /**
     * 分享状态：1-有效，2-已禁用，3-已过期
     */
    @TableField("status")
    private Integer status;
    
    /**
     * 访问权限：1-仅查看，2-可下载，3-可预览+下载
     */
    @TableField("access_permission")
    private Integer accessPermission;
    
    /**
     * 最大访问次数（0表示不限制）
     */
    @TableField("max_access_count")
    private Integer maxAccessCount;
    
    /**
     * 当前访问次数
     */
    @TableField("current_access_count")
    private Integer currentAccessCount;
    
    /**
     * 最大下载次数（0表示不限制）
     */
    @TableField("max_download_count")
    private Integer maxDownloadCount;
    
    /**
     * 当前下载次数
     */
    @TableField("current_download_count")
    private Integer currentDownloadCount;
    
    /**
     * 分享有效期开始时间
     */
    @TableField("valid_from")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime validFrom;
    
    /**
     * 分享有效期结束时间
     */
    @TableField("valid_until")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime validUntil;
    
    /**
     * 允许访问的IP地址列表（JSON格式，可选）
     */
    @TableField("allowed_ips")
    private String allowedIps;
    
    /**
     * 允许访问的用户ID列表（JSON格式，可选）
     */
    @TableField("allowed_users")
    private String allowedUsers;
    
    /**
     * 分享创建者ID
     */
    @TableField("creator_id")
    private String creatorId;
    
    /**
     * 分享创建者名称
     */
    @TableField("creator_name")
    private String creatorName;
    
    /**
     * 最后访问时间
     */
    @TableField("last_access_time")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime lastAccessTime;
    
    /**
     * 最后访问IP
     */
    @TableField("last_access_ip")
    private String lastAccessIp;
    
    /**
     * 分享描述
     */
    @TableField("description")
    private String description;
    
    /**
     * 扩展属性（JSON格式存储）
     */
    @TableField("extra_attributes")
    private String extraAttributes;
    
    // ==================== 便捷方法 ====================
    
    /**
     * 判断分享链接是否有效
     */
    public boolean isValid() {
        if (status == null || status != 1) {
            return false;
        }
        
        LocalDateTime now = LocalDateTime.now();
        
        // 检查有效期
        if (validFrom != null && now.isBefore(validFrom)) {
            return false;
        }
        if (validUntil != null && now.isAfter(validUntil)) {
            return false;
        }
        
        // 检查访问次数限制
        if (maxAccessCount != null && maxAccessCount > 0 && 
            currentAccessCount != null && currentAccessCount >= maxAccessCount) {
            return false;
        }
        
        return true;
    }
    
    /**
     * 判断是否已过期
     */
    public boolean isExpired() {
        if (validUntil == null) {
            return false;
        }
        return LocalDateTime.now().isAfter(validUntil);
    }
    
    /**
     * 判断是否需要密码
     */
    public boolean requiresPassword() {
        return shareType != null && shareType == 2 && 
               sharePassword != null && !sharePassword.trim().isEmpty();
    }
    
    /**
     * 判断是否为一次性链接
     */
    public boolean isOneTimeLink() {
        return shareType != null && shareType == 3;
    }
    
    /**
     * 判断是否可以下载
     */
    public boolean canDownload() {
        return accessPermission != null && (accessPermission == 2 || accessPermission == 3);
    }
    
    /**
     * 判断是否可以预览
     */
    public boolean canPreview() {
        return accessPermission != null && (accessPermission == 1 || accessPermission == 3);
    }
    
    /**
     * 判断是否还能访问（检查访问次数限制）
     */
    public boolean canAccess() {
        if (maxAccessCount == null || maxAccessCount <= 0) {
            return true; // 无限制
        }
        return currentAccessCount == null || currentAccessCount < maxAccessCount;
    }
    
    /**
     * 判断是否还能下载（检查下载次数限制）
     */
    public boolean canDownloadMore() {
        if (!canDownload()) {
            return false;
        }
        if (maxDownloadCount == null || maxDownloadCount <= 0) {
            return true; // 无限制
        }
        return currentDownloadCount == null || currentDownloadCount < maxDownloadCount;
    }
    
    /**
     * 增加访问次数
     */
    public void incrementAccessCount() {
        if (currentAccessCount == null) {
            currentAccessCount = 1;
        } else {
            currentAccessCount++;
        }
    }
    
    /**
     * 增加下载次数
     */
    public void incrementDownloadCount() {
        if (currentDownloadCount == null) {
            currentDownloadCount = 1;
        } else {
            currentDownloadCount++;
        }
    }
    
    // ==================== Getter/Setter ====================
    
    public String getId() {
        return id;
    }
    
    public void setId(String id) {
        this.id = id;
    }
    
    public String getFileId() {
        return fileId;
    }
    
    public void setFileId(String fileId) {
        this.fileId = fileId;
    }
    
    public String getShareCode() {
        return shareCode;
    }
    
    public void setShareCode(String shareCode) {
        this.shareCode = shareCode;
    }
    
    public String getSharePassword() {
        return sharePassword;
    }
    
    public void setSharePassword(String sharePassword) {
        this.sharePassword = sharePassword;
    }
    
    public Integer getShareType() {
        return shareType;
    }
    
    public void setShareType(Integer shareType) {
        this.shareType = shareType;
    }
    
    public Integer getStatus() {
        return status;
    }
    
    public void setStatus(Integer status) {
        this.status = status;
    }
    
    public Integer getAccessPermission() {
        return accessPermission;
    }
    
    public void setAccessPermission(Integer accessPermission) {
        this.accessPermission = accessPermission;
    }
    
    public Integer getMaxAccessCount() {
        return maxAccessCount;
    }
    
    public void setMaxAccessCount(Integer maxAccessCount) {
        this.maxAccessCount = maxAccessCount;
    }
    
    public Integer getCurrentAccessCount() {
        return currentAccessCount;
    }
    
    public void setCurrentAccessCount(Integer currentAccessCount) {
        this.currentAccessCount = currentAccessCount;
    }
    
    public Integer getMaxDownloadCount() {
        return maxDownloadCount;
    }
    
    public void setMaxDownloadCount(Integer maxDownloadCount) {
        this.maxDownloadCount = maxDownloadCount;
    }
    
    public Integer getCurrentDownloadCount() {
        return currentDownloadCount;
    }
    
    public void setCurrentDownloadCount(Integer currentDownloadCount) {
        this.currentDownloadCount = currentDownloadCount;
    }
    
    public LocalDateTime getValidFrom() {
        return validFrom;
    }
    
    public void setValidFrom(LocalDateTime validFrom) {
        this.validFrom = validFrom;
    }
    
    public LocalDateTime getValidUntil() {
        return validUntil;
    }
    
    public void setValidUntil(LocalDateTime validUntil) {
        this.validUntil = validUntil;
    }
    
    public String getAllowedIps() {
        return allowedIps;
    }
    
    public void setAllowedIps(String allowedIps) {
        this.allowedIps = allowedIps;
    }
    
    public String getAllowedUsers() {
        return allowedUsers;
    }
    
    public void setAllowedUsers(String allowedUsers) {
        this.allowedUsers = allowedUsers;
    }
    
    public String getCreatorId() {
        return creatorId;
    }
    
    public void setCreatorId(String creatorId) {
        this.creatorId = creatorId;
    }
    
    public String getCreatorName() {
        return creatorName;
    }
    
    public void setCreatorName(String creatorName) {
        this.creatorName = creatorName;
    }
    
    public LocalDateTime getLastAccessTime() {
        return lastAccessTime;
    }
    
    public void setLastAccessTime(LocalDateTime lastAccessTime) {
        this.lastAccessTime = lastAccessTime;
    }
    
    public String getLastAccessIp() {
        return lastAccessIp;
    }
    
    public void setLastAccessIp(String lastAccessIp) {
        this.lastAccessIp = lastAccessIp;
    }
    
    public String getDescription() {
        return description;
    }
    
    public void setDescription(String description) {
        this.description = description;
    }
    
    public String getExtraAttributes() {
        return extraAttributes;
    }
    
    public void setExtraAttributes(String extraAttributes) {
        this.extraAttributes = extraAttributes;
    }
    
    @Override
    public String toString() {
        return "ShareLink{" +
                "id='" + id + '\'' +
                ", fileId='" + fileId + '\'' +
                ", shareCode='" + shareCode + '\'' +
                ", shareType=" + shareType +
                ", status=" + status +
                ", accessPermission=" + accessPermission +
                ", maxAccessCount=" + maxAccessCount +
                ", currentAccessCount=" + currentAccessCount +
                ", validFrom=" + validFrom +
                ", validUntil=" + validUntil +
                ", creatorId='" + creatorId + '\'' +
                ", creatorName='" + creatorName + '\'' +
                '}';
    }
}
